﻿using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.Security;
using Models;

/// <summary>
///SmsTool 的摘要说明
/// </summary>
public class SmsTool
{
    /// <summary>
    /// 短信接口帐号
    /// </summary>
    private const string ACCOUNT = "ln";
    /// <summary>
    /// 短信接口密码
    /// </summary>
    private const string PWD = "ln8753dd";

    public SmsTool()
    {
        //
        //TODO: 在此处添加构造函数逻辑
        //
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="phoneNumber">电话号码</param>
    /// <param name="message">短信内容</param>
    /// <param name="msg">结果提示</param>
    /// <returns></returns>
    public bool SendSmsCode(string phoneNumber, string message, out string msg, out string vcode)
    {
        msg = "";
        vcode = "";
        if (string.IsNullOrEmpty(message))
        {
            return false;
        }
        int code = GetRandomCode();
        vcode = code.ToString();
        return SendSms(phoneNumber, string.Format(message, code), "getcode", 0, out msg);
    }

    public int GetRandomCode()
    {
        Random ran = new Random(DateTime.Now.Millisecond);
        int code = ran.Next(1342, 9999);
        return code;
    }

    //public bool sendOrderNoticeSms(H_reservation order)
    //{
    //    string url = "http://www.zhaotongtour.com/m/skcode.aspx?id=" + order.id;
    //    try
    //    {
    //        var u = dwz.com.dwztool.BaiduApisShorturl(url);
    //        if (u.urls != null && u.urls.Length > 0)
    //        {
    //            if (!string.IsNullOrEmpty(u.urls[0].url_short))
    //            {
    //                url = u.urls[0].url_short;
    //            }
    //        }
    //        Cms.Vows.Logger.WriteLogTxt(u.ToJson(), "dwz");
    //        string msg = "";
    //        string content = "您已成功订购了电子票. 订单号:" + order.orderid + "," + order.title + order.type + url + " .持此票到指定商家换票或消费";
    //        SendSms(order.phone, content, "ordernotice", order.id, out msg);
    //        return msg == "0";
    //    }
    //    catch
    //    {

    //    }
    //    return false;
    //}


   




    /// <summary>
    /// 参数（带*为必须）	说明	参数
    ///* userName	       用户名	固定为”ln“
    ///* orderNo	        单号	唯一值，不超过10字节
    ///* phone	          电话号码	多个号码用引文逗号分隔
    ///* sendInfo	      短信内容	注意不得发送营销短信，不得带有敏感字
    ///* auth	          加密字符串	将“userName+ orderNo+ phone+ sendInfo+密钥”作为一个新字符串进行MD5加密
    ///密钥	“ln”的用户名固定密钥为”112725“（不含双引号）    
    ///
    /// 错误码	错误侧	          错误描述
    ///   -2	客户端	         客户端异常
    ///-9000		            数据格式错误,数据超出数据库允许范围
    ///-9001	客户端,所有业务	序列号格式错误
    ///-9002	客户端,所有业务	密码格式错误
    ///-9003	客户端,所有业务	客户端Key格式错误
    ///-9016	客户端,发送业务	发送短信包大小超出范围
    ///-9017	客户端,发送业务	发送短信内容格式错误
    ///-9018	客户端,发送业务	发送短信扩展号格式错误
    ///-9019	客户端,发送业务	发送短信优先级格式错误
    ///-9020	客户端,发送业务	发送短信手机号格式错误
    ///-9021	客户端,发送业务	发送短信定时时间格式错误
    ///-9022	客户端,发送业务	发送短信唯一序列值错误
    ///-5001	客户端	        参数缺失
    ///-5002	客户端	        加密信息错误
    ///
    ///    0	服务器端	    成功
    ///   -1	服务器端	    系统异常
    ///  -101	服务器端	    命令不被支持
    /// </summary>
    /// <param name="phoneNumber">电话号码</param>
    /// <param name="message">短信内容</param>
    /// /// <param name="type">短信类型</param>
    /// <param name="msg">结果提示</param>
    /// <returns>发送是否成功</returns>
    public bool SendSms(string phoneNumber, string message, string type, int forid, out string msg)
    {
        msg = "";
        if (!Regex.IsMatch(phoneNumber, @"^\d+$"))
        {
            msg = "手机号错误";
            return false;
        }
        if (string.IsNullOrEmpty(message))
        {
            msg = "短信内容不能为空";
            return false;
        }
        if (message.Length > 100)
        {
            msg = "短信内容过长";
            return false;
        }
        Entities db = new Entities();
        //SendSms sms = null;// db.SendSms.Where(x => x.SPhone == phoneNumber).OrderByDescending(x => x.DTime).FirstOrDefault();
        /*if (sms != null && sms.DTime != null && sms.DTime.Value.AddSeconds(60) > DateTime.Now)
        {
            msg = "短信过于频繁";
            return false;
        }*/
        //message = Regex.Replace(message, @"[\[\]\{\}【】\s]", "");
        //sms = new SendSms();
        //sms.SPhone = phoneNumber;
        //sms.SContent = message;
        //sms.DTime = DateTime.Now;
        //sms.Stype = type;
        //sms.NForId = forid;
        //sms.SOrderNO = getSmsNO(db);
        //db.SendSms.AddObject(sms);

        //string chargeURL = "http://top.hd998.org:8081/sms/interface/dosend.aspx?";
        //string chargeURL = "http://120.24.85.74:8081/sms/interface/dosend.aspx?"; //使用ip，提高访问稳定性
        string chargeURL = "http://xxt.wzinfo.cc/interface/dosend.aspx?"; //使用ip，提高访问稳定性
        string userName = ACCOUNT;
        string desKey = PWD;

        string authOrigString = userName + phoneNumber + message + GetOrderNo() + desKey;
       
        //string truePwd = BitConverter.ToString(md5.ComputeHash(Encoding.UTF8.GetBytes(authOrigString))).Replace("-", null);
        //string truePwd = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(authOrigString, "MD5").ToUpper();
        string chargeURLString = chargeURL + "user=" + userName + "&orderNo=" + GetOrderNo() + "&phone=" + phoneNumber + "&sendInfo=" + message + "&auth=" + FormsAuthentication.HashPasswordForStoringInConfigFile(authOrigString, "MD5").ToUpper();
        //System.IO.File.WriteAllText("f:\\xwgc.txt", authOrigString);
        //string chargeURLString = chargeURL + "user=" + userName + "&orderNo=" + GetOrderNo() + "&phone=" + phoneNumber + "&sendInfo=" + message + "&auth=" + truePwd;

        try
        {
            HttpWebRequest request = WebRequest.Create(chargeURLString) as HttpWebRequest;
            request.Method = "get";
            request.KeepAlive = false;
            request.Timeout = 15000;
            string result = "";
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            Stream responseStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);

            //string result = reader.ReadToEnd();
            //var streamWriter = new StreamWriter(request.GetRequestStream());
            //string result = streamWriter.ToString();
            //if (result != "0")
            //    {
            //        msg = result;
            //        //Cms.Vows.Logger.WriteLogTxt("发送错误-" + result + "//" + chargeURLString, "SendSms");
            //    }
            //    else
            //    {
            //        msg = "发送成功";
            //    }
            //sms.SResult = result;
            //db.SaveChanges();
            return true;
        }
        catch (Exception ex)
        {
            msg = ex.Message;
            return false;
        }
    }

    public string GetOrderNo()
    {
        string Result = "";
        Result = "Ln" +DateTime.Now.ToString("yyyyMMddhhmmss")+ DateTime.Now.Millisecond;
        return Result;
    }

    private string getSmsNO(Entities db)
    {
        DateTime A = DateTime.Parse("2016/01/01 00:00:00");
        var p = DateTime.Now - A;

        string orderId = string.Format("{0}{1}{2}{3}", p.Days, p.Hours, p.Minutes, p.Seconds); ;
        //if (db.SendSms.Any(x => x.SOrderNO == orderId))
        //{
        //    return getSmsNO(db);
        //}
        return orderId;
    }
}